package felix.things.router.mqtt.server.broker.config.credentials;

import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslHandler;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author Felix
 * @date 2019/7/27
 */
@Data
@Component
@ConditionalOnProperty(prefix = "spring.mqtt.broker.credentials", value = "type", havingValue = "cert.JKS")
@ConfigurationProperties(prefix = "spring.mqtt.broker.credentials", ignoreInvalidFields = true)
public class CertJKSServerCredentials implements MqttServerCredentials {

    private String sslProtocol;
    private String keyStoreFile;
    private String keyStorePassword;
    private String keyPassword;
    private String keyStoreType;

    @Override
    public void configureSsl(ChannelPipeline channelPipeline, SocketChannel socketChannel) throws Exception {
        InputStream tsFileInputStream = this.getClass().getClassLoader().getResourceAsStream(keyStoreFile);
        InputStream ksFileInputStream = this.getClass().getClassLoader().getResourceAsStream(keyStoreFile);

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(tsFileInputStream, keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        ks.load(ksFileInputStream, keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        if (StringUtils.isEmpty(sslProtocol)) {
            sslProtocol = "TLS";
        }
        SSLContext sslContext = SSLContext.getInstance(sslProtocol);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        SslHandler sslHandler = new SslHandler(sslEngine);
        channelPipeline.addLast(sslHandler);
    }


    private TrustManager getX509TrustManager(TrustManagerFactory tmf) throws Exception {
        X509TrustManager x509Tm = null;
        for (TrustManager tm : tmf.getTrustManagers()) {
            if (tm instanceof X509TrustManager) {
                x509Tm = (X509TrustManager) tm;
                break;
            }
        }
        return new MqttX509TrustManager(x509Tm);
    }

    static class MqttX509TrustManager implements X509TrustManager {

        private final X509TrustManager trustManager;

        MqttX509TrustManager(X509TrustManager trustManager) {
            this.trustManager = trustManager;
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return trustManager.getAcceptedIssuers();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
            trustManager.checkServerTrusted(chain, authType);
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
            /*String credentialsBody = null;
            for (X509Certificate cert : chain) {
                try {
                   String strCert = SslUtil.getX509CertificateString(cert);
                    String sha3Hash = EncryptionUtil.getSha3Hash(strCert);
                    final String[] credentialsBodyHolder = new String[1];
                    CountDownLatch latch = new CountDownLatch(1);
                    transportService.process(TransportProtos.ValidateDeviceX509CertRequestMsg.newBuilder().setHash(sha3Hash).build(),
                            new TransportServiceCallback<TransportProtos.ValidateDeviceCredentialsResponseMsg>() {
                                @Override
                                public void onSuccess(TransportProtos.ValidateDeviceCredentialsResponseMsg msg) {
                                    if (!StringUtils.isEmpty(msg.getCredentialsBody())) {
                                        credentialsBodyHolder[0] = msg.getCredentialsBody();
                                    }
                                    latch.countDown();
                                }

                                @Override
                                public void onError(Throwable e) {
                                    log.error(e.getMessage(), e);
                                    latch.countDown();
                                }
                            });
                    latch.await(10, TimeUnit.SECONDS);
                    if (strCert.equals(credentialsBodyHolder[0])) {
                        credentialsBody = credentialsBodyHolder[0];
                        break;
                    }
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (credentialsBody == null) {
                throw new CertificateException("Invalid Device Certificate");
            }*/
        }
    }
}
